package com.lmf.webservice.marshaller;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;

/**
 * 测试利用marshaller，unmarshaller来实现Java类与xml文件的转换
 */
public class Main_JAXB {
    public static void main(String[] args) {
        myMarshaller();
        System.out.println("---------------------------");
        unMarshaller();
    }

    /**
     * 将Java类转化为xml文件
     */
    public static void myMarshaller(){
        try {
            //根据Java类，获取一个JAXB实例对象
            JAXBContext jaxbContext = JAXBContext.newInstance(Book.class);
            //获取一个marshaller对象
            Marshaller marshaller = jaxbContext.createMarshaller();
            //设置marshaller属性值
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);
            marshaller.setProperty(Marshaller.JAXB_ENCODING,"utf-8");
            //将一个Java对象解析为xml文件，并输出
            marshaller.marshal(new Book("Java编程思想",22.3d,12),System.out);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将xml文件解析为Java类，对象
     */
    public static void unMarshaller(){
//        String xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?><book><bookName>Java编程思想</bookName><bookid>12</bookid><price>22.3</price></book>";

        String xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>\n" +
                "<book>\n" +
                "    <bookName>Java编程思想</bookName>\n" +
                "    <bookid>12</bookid>\n" +
                "    <price>22.3</price>\n" +
                "</book>";
        try {
            //获取一个jaxb实例对象
            JAXBContext jaxbContext = JAXBContext.newInstance(Book.class);
            //再创建一个unmarshaller对象
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            //利用unmarshaller解析xml文件
            Object unmarshal = unmarshaller.unmarshal(new StringReader(xmlString));
            //强制转换为原本类型
            Book book = (Book) unmarshal;
            //打印输出
            System.out.println(book.toString());
        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }
}
